/*******************************************************************************
 * Copyright (c) 2011 Irineu Martins de Lima Moura (imlm2).
 * This file is part of JBeat.
 * 
 *     JBeat is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     JBeat is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with JBeat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Irineu Martins de Lima Moura (imlm2) - initial API and implementation
 ******************************************************************************/
package br.ufpe.cin.imlm2.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

public class CPEntryFinder implements FileVisitor<Path>{

	private List<String> paths;
	private boolean recursively;

	public CPEntryFinder() {
		paths = new ArrayList<>();
	}

	public CPEntryFinder(boolean rec) {
		this();
		this.recursively = rec;
	}



	public void findJars(File searchPath){
		if(searchPath.exists()){
			this.visit(searchPath);
		}
	}
	
	private void visit(File root){
		if(root.isDirectory()){
			for (File f : root.listFiles()) {
				if(this.recursively) {
					this.visit(f);					
				} else if(isEntryFile(f)){
					this.paths.add(f.getAbsolutePath());
				} 
			}
		} else if(isEntryFile(root)){
			this.paths.add(root.getAbsolutePath());
		}
	}

	private boolean isEntryFile(File root) {
		return root.isFile() && (root.getName().endsWith(".jar") || root.getName().endsWith(".class"));
	}
	
	public List<String> getPaths() {
		return paths;
	}

	@Override
	public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
			throws IOException {
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
			throws IOException {
		return null;
	}

	@Override
	public FileVisitResult visitFileFailed(Path file, IOException exc)
			throws IOException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public FileVisitResult postVisitDirectory(Path dir, IOException exc)
			throws IOException {
		// TODO Auto-generated method stub
		return null;
	}
	
}
